#include <ncurses.h>
#include "Curses.h"
#include "Level.h"
#include "EntityManager.h"
#include "Window.h"

void EntityManager::removeEntity(Entity* entity) {
	std::vector<Entity *>::iterator i;
	for (i = m_entities.begin(); i != m_entities.end(); ++i) {
		if ((*i) == entity) {
			m_entities.erase(i);
			break;
		}
	}
}

void EntityManager::addCharacter(Character* character) {
	addEntity(character);
	m_characters.push_back(character);
}

void EntityManager::addItem(Item* item) {
	addEntity(item);
	m_items.push_back(item);
}

void EntityManager::removeItem(Item* item) {
	std::vector<Item *>::iterator i;
	for (i = m_items.begin(); i != m_items.end(); ++i) {
		if ((*i) == item) {
			m_items.erase(i);
			break;
		}
	}
	removeEntity(item);
}

std::vector<Item *> EntityManager::getItemsAt(int x, int y, Level* currentLevel) const {
	std::vector<Item *> resultVector;
	std::vector<Item *>::const_iterator i;
	for (i = m_items.begin(); i != m_items.end(); ++i) {
		if ( (*i)->coord().x == x 
			&& (*i)->coord().y == y 
			&& (*i)->getCurrentLevel() == currentLevel)
		{
			resultVector.push_back(*i);
		}
	}
	return resultVector;
}

void EntityManager::resetActions() {
	std::vector<Character *>::iterator i;
	for (i = m_characters.begin(); i != m_characters.end(); ++i) {
		(*i)->resetActionPoints();
	}
}

void EntityManager::outputEntities(Level* currentLevel) const {
	
	Curses curses = Curses::instance();
	
	std::vector<Entity*>::const_iterator i;
	for (i = m_entities.begin(); i != m_entities.end(); ++i) {
		if ((*i)->getCurrentLevel() == currentLevel) {
			// TODO: Also check whether they are in fog of war or not.
			
			// If this method is called, the MapWindow should be on
			// top of stack.
			Window* mapWindow = curses.topWindow();
			mapWindow->enableAttributes(COLOR_PAIR((*i)->symbol().color));
			curses.putchar(mapWindow, 
				(*i)->coord().x + 1, 
				(*i)->coord().y + 1, 
				(*i)->symbol().symbol);
			mapWindow->disableAttributes(COLOR_PAIR((*i)->symbol().color));
			
		}
	}
	
}

bool EntityManager::actionsRemaining() const {
	std::vector<Character *>::const_iterator i;
	for (i = m_characters.begin(); i != m_characters.end(); ++i) {
		if ((*i)->remainingActionPoints() > 0)
			return true;
	}
	return false;
}
